package com.love.marriage.userCommissionWithdrawal.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.love.marriage.common.enums.ResultEnum;
import com.love.marriage.common.exceptions.SystemException;
import com.love.marriage.userCommissionBalance.service.UserCommissionBalanceService;
import com.love.marriage.userCommissionBalance.vo.UserCommissionBalanceVo;
import com.love.marriage.userCommissionWithdrawal.entity.UserCommissionWithdrawal;
import com.love.marriage.userCommissionWithdrawal.mapper.UserCommissionWithdrawalMapper;
import com.love.marriage.userCommissionWithdrawal.service.UserCommissionWithdrawalService;
import com.love.marriage.userCommissionWithdrawal.vo.UserCommissionWithdrawalExportVo;
import com.love.marriage.userCommissionWithdrawal.vo.UserCommissionWithdrawalVo;
import com.love.marriage.userCommissionWithdrawalHistory.service.UserCommissionWithdrawalHistoryService;
import com.love.marriage.userCommissionWithdrawalHistory.vo.UserCommissionWithdrawalHistoryVo;
import com.love.marriage.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * description:  用户提现回佣金额历史表服务实现类
 * author:       mybatisPlus
 * createDate:   2025-01-29 19:43:00
 * version:      1.0.0
 */
@Service
@RequiredArgsConstructor
public class UserCommissionWithdrawalServiceImp extends ServiceImpl<UserCommissionWithdrawalMapper, UserCommissionWithdrawal> implements UserCommissionWithdrawalService {

    private final UserCommissionWithdrawalMapper userCommissionWithdrawalMapper;

    private final UserCommissionWithdrawalHistoryService userCommissionWithdrawalHistoryService;

    private final UserCommissionBalanceService userCommissionBalanceService;

    @Override
    public Page<UserCommissionWithdrawalVo> getPage(Long pageNum, Long pageSize, UserCommissionWithdrawalVo userCommissionWithdrawalVo) {
        Page<UserCommissionWithdrawalVo> page = new Page<>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
        return userCommissionWithdrawalMapper.getPage(page, userCommissionWithdrawalVo);
    }

    @Override
    public List<UserCommissionWithdrawalVo> getList(UserCommissionWithdrawalVo userCommissionWithdrawalVo) {
        return userCommissionWithdrawalMapper.getList(userCommissionWithdrawalVo);
    }

    @Override
    public UserCommissionWithdrawalVo queryUserCommissionWithdrawal(Long id) {
        return userCommissionWithdrawalMapper.queryUserCommissionWithdrawal(id);
    }

    @Override
    public UserCommissionWithdrawalVo addUserCommissionWithdrawal(UserCommissionWithdrawalVo userCommissionWithdrawalVo) {
        UserCommissionWithdrawal userCommissionWithdrawal = new UserCommissionWithdrawal();
        BeanUtils.copyProperties(userCommissionWithdrawalVo, userCommissionWithdrawal);
        userCommissionWithdrawalMapper.insert(userCommissionWithdrawal);
        UserCommissionWithdrawalVo res = new UserCommissionWithdrawalVo();
        BeanUtils.copyProperties(userCommissionWithdrawal, res);
        return res;
    }

    @Override
    public UserCommissionWithdrawalVo updateUserCommissionWithdrawal(UserCommissionWithdrawalVo userCommissionWithdrawalVo) {
        UserCommissionWithdrawal userCommissionWithdrawal = new UserCommissionWithdrawal();
        BeanUtils.copyProperties(userCommissionWithdrawalVo, userCommissionWithdrawal);
        userCommissionWithdrawalMapper.updateById(userCommissionWithdrawal);
        return userCommissionWithdrawalVo;
    }

    @Override
    public Boolean deleteUserCommissionWithdrawal(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return true;
        }
        List<String> idArr = Arrays.asList(ids.split(","));
        userCommissionWithdrawalMapper.deleteBatchIds(idArr);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean submitUserCommissionWithdrawal(Long id, String status, String message) {
        // 更新记录表
        UserCommissionWithdrawal db = userCommissionWithdrawalMapper.selectById(id);
        db.setStatus(status);
        db.updateById();
        if ("COMPLETED".equals(status)) {
            // 扣除用户回佣余额
            UserCommissionBalanceVo userCommissionBalanceVo = userCommissionBalanceService.queryByUserId(db.getUserId());
            if (userCommissionBalanceVo == null || userCommissionBalanceVo.getCurrentBalance().compareTo(db.getWithdrawalAmount()) < 0) {
                throw new SystemException(ResultEnum.USER_NO_ENOUGH_BALANCE);
            }
            userCommissionBalanceVo.setCurrentBalance(userCommissionBalanceVo.getCurrentBalance().subtract(db.getWithdrawalAmount()));
            userCommissionBalanceService.updateUserCommissionBalance(userCommissionBalanceVo);
        }
        // 保存用户提现记录
        UserCommissionWithdrawalHistoryVo userCommissionWithdrawalHistoryVo = new UserCommissionWithdrawalHistoryVo();
        userCommissionWithdrawalHistoryVo.setUserId(db.getUserId());
        userCommissionWithdrawalHistoryVo.setWithdrawalAmount(db.getWithdrawalAmount());
        userCommissionWithdrawalHistoryVo.setWithdrawalDate(LocalDateTime.now());
        userCommissionWithdrawalHistoryVo.setStatus(status);
        userCommissionWithdrawalHistoryVo.setNotes(StringUtils.isNotBlank(message) ? message : "用户提现");
        userCommissionWithdrawalHistoryVo.setPartnerTradeNo(db.getPartnerTradeNo());
        userCommissionWithdrawalHistoryService.addUserCommissionWithdrawalHistory(userCommissionWithdrawalHistoryVo);
        return true;
    }

    private String getStatus(String status) {
        switch (status) {
            case "PENDING":
                return "待审核";
            case "REJECTED":
                return "已拒绝";
            case "CANCEL":
                return "取消";
            case "COMPLETED":
                return "已完成";
            default:
                return "未知状态";
        }
    }

    @Override
    public UserCommissionWithdrawalVo queryUserCommissionWithdrawalInfo(UserCommissionWithdrawalVo userCommissionWithdrawalVo) {
        return userCommissionWithdrawalMapper.queryUserCommissionWithdrawalInfo(userCommissionWithdrawalVo);
    }

    @Override
    public void export(UserCommissionWithdrawalVo userCommissionWithdrawalVo, HttpServletResponse response) throws Exception {
        List<UserCommissionWithdrawalVo> list = userCommissionWithdrawalMapper.getList(userCommissionWithdrawalVo);
        List<UserCommissionWithdrawalExportVo> exportList = list.stream().map(item -> {
            UserCommissionWithdrawalExportVo vo = new UserCommissionWithdrawalExportVo();
            vo.setCode(item.getCode());
            vo.setPhone(item.getPhone());
            vo.setWithdrawalAmount(item.getWithdrawalAmount());
            vo.setWithdrawalDate(item.getWithdrawalDate());
            vo.setStatus(getStatus(item.getStatus()));
            vo.setNotes(item.getNotes());
            vo.setPartnerTradeNo(item.getPartnerTradeNo());
            return vo;
        }).collect(Collectors.toList());

        ExportParams exportParams = new ExportParams("佣金提现", "提现记录");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, UserCommissionWithdrawalExportVo.class, exportList);
        response.setContentType("application/vnd.ms-excel; charset=UTF-8");
        response.setHeader("Content-Disposition", "filename.xls");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        workbook.write(response.getOutputStream());
        response.flushBuffer();
        workbook.close();
    }
}
